/**
 * SPDX-FileCopyrightText: 2023-2025 Sangfor Technologies Inc.
 * SPDX-License-Identifier: Mulan PSL v2
 */
<template>
    <sf-form
        ref="form"
        class="set_algorithm_form"
        :label-width="120">
        <sf-form-item>
            <sf-fieldlabel>
                <lang>训练任务名称</lang>
            </sf-fieldlabel>
            <sf-textfield
                ref="fieldName"
                v-model="submitData.taskName"
                :default-width="defaultWidth"
                :max-length="30"
                :allow-blank="false"
                :utf8-length="false"
                vtype="name"
                :placeholder="_('请输入训练任务名称')" />
        </sf-form-item>
        <sf-form-item v-if="submitData.isAutoMl === 1">
            <sf-fieldlabel>
                <lang>选择算法模板</lang>
            </sf-fieldlabel>
            <span class="quick-algorithm">快速算法</span>
        </sf-form-item>
        <sf-form-item v-else>
            <sf-fieldlabel>
                <lang>选择算法模板</lang>
            </sf-fieldlabel>
            <sf-select-tree
                v-model="submitData.algorithmId"
                :default-width="defaultWidth"
                :allow-blank="false"
                @change="_selectAlgorithm">
                <sf-grid>
                    <sf-tree-table
                        :options="typeTreeOptions"
                        :default-height="300">
                        <sf-tree-column
                            data-index="id"
                            :renderer="_typeTreeRender" />
                    </sf-tree-table>
                </sf-grid>
            </sf-select-tree>
        </sf-form-item>
        <div v-if="showConfigJson"
             class="algorithm-config__container">
            <!-- <span>自动优化<sf-switch v-model="is_on"
                                 class="m-l5" /></span> -->
            <div
                class="algorithm-config__form">
                <sf-form-item v-for="(item,index) in algorithmConfigList"
                              :key="index">
                    <sf-fieldlabel>
                        <lang>{{ item.paramName }}</lang>
                    </sf-fieldlabel>
                    <sf-textfield
                        v-model="item.value"
                        :default-width="240"
                        :allow-blank="false"
                        :utf8length="false" />
                    <sf-fieldtip>
                        <lang>{{ item.description }}</lang>
                    </sf-fieldtip>
                </sf-form-item>
            </div>
        </div>

        <!-- <div class="time-update__container">
            <sf-form-item class="time_update_form">
                <sf-fieldlabel>
                    <lang>定时更新训练</lang>
                </sf-fieldlabel>
                <sf-radio-group v-model="submitData.periodic"
                                class="m-l3">
                    <sf-radio name="periodic"
                              class="m-t1 m-l3"
                              :check-value="0">
                        <lang>禁用</lang>
                        <sf-fieldtip>
                            <lang>训练任务仅执行一次。</lang>
                        </sf-fieldtip>
                    </sf-radio>
                    <sf-radio name="periodic"
                            class="m-t1"
                            :check-value="1">
                        <lang>启用</lang>
                        <sf-fieldtip>
                            <lang>训练任务定时周期执行。</lang>
                        </sf-fieldtip>
                    </sf-radio>
                </sf-radio-group>
            </sf-form-item>
            <div v-if="submitData.periodic===1"
                 class="time_update__content">
                <div class="config-box">
                    <div class="config-title">
                        <lang>任务设置</lang>
                    </div>
                    <sf-form-item class="form-item--first">
                        <sf-fieldlabel>
                            <lang>执行时间</lang>
                        </sf-fieldlabel>
                        <sf-datefield v-model="dateTime"
                                      type="dateTimeRange"
                                      :show-second="true"
                                      :default-width="326"
                                      placeholder="不限" />
                    </sf-form-item>
                    <sf-form-item class="form-item--first">
                        <sf-fieldlabel>
                            <lang>更新周期</lang>
                        </sf-fieldlabel>
                        <span><lang>每</lang></span>
                        <sf-numberfield ref="timeLength"
                                        v-model="submitData.timeLength"
                                        :default-width="130"
                                        :allow-blank="false"
                                        :allow-decimals="false"
                                        :placeholder="_('请输入整数')"
                                        :validator="_timeLengthValidator"
                                        :min-value="1" />
                        <sf-select v-model="submitData.timeUnit"
                                   :default-width="177"
                                   :allow-search="true"
                                   :allow-blank="false"
                                   :options="timeUnitList" />
                    </sf-form-item>
                </div>
                <div class="config-box">
                    <div class="config-title">
                        <lang>数据设置</lang>
                        <i id="sf-id-192"
                           class="sfv-fieldtip  sfv-fieldtip_icon sf-comp-iconfont icon-comp-info"
                           sfv="">
                            <div class="update-demo sfv-layer">
                                <div class="update-demo__img"></div>
                                <div class="sfv-layer-arrow"
                                     style="top: -0.5px;"></div>
                            </div>
                        </i>
                    </div>
                    <sf-form-item class="form-item--first">
                        <sf-fieldlabel>
                            <lang>数据源时间字段</lang>
                        </sf-fieldlabel>
                        <sf-select v-model="submitData.dataField"
                                   :default-width="326"
                                   :allow-search="true"
                                   :allow-blank="false"
                                   :options="timeFieldList" />
                    </sf-form-item>
                    <sf-form-item class="form-item--first">
                        <sf-fieldlabel>
                            <lang>数据源取值范围</lang>
                        </sf-fieldlabel>
                        <sf-numberfield v-model="submitData.dataLength"
                                        :default-width="146"
                                        :allow-blank="false"
                                        :allow-decimals="false"
                                        :placeholder="_('请输入整数')"
                                        :min-value="1" />
                        <sf-select v-model="submitData.dataUnit"
                                   :default-width="177"
                                   :allow-search="true"
                                   :allow-blank="false"
                                   :options="timeUnitList" />
                    </sf-form-item>
                </div>
            </div>
        </div> -->
        <sf-form-item>
            <sf-fieldlabel>
                <lang>训练任务描述</lang>
            </sf-fieldlabel>
            <sf-textarea
                v-model="submitData.description"
                :default-width="defaultWidth"
                :max-length="300"
                :utf8-length="false" />
        </sf-form-item>
    </sf-form>
</template>
<script>
import { deepClone } from 'src/util/deep_clone';
const DEFAULT_WIDTH = 456;

import moment from 'moment';

const DEFAULT_FEILD_WIDTH = 88;

let startTime = `${moment().format('YYYY-MM-DD')} 22:00:00`;
let endTime =  `${moment().add(1, 'days').format('YYYY-MM-DD')} 22:00:00`;


// import TRAINING_INFO from '../../const';

const TRAINING_INFO = {
    taskName: '',
    description: '',
    algorithmId:0,
    configJson:'',
    periodic:0,
    timeLength:1,
    timeUnit:'day',
    dataField:'',
    dataLength:5,
    dataUnit:'day',
    startTime,
    endTime,
    algorithmName:'',
    isAutoMl:0 //1代表快速算法，0代表自定义算法
};

import {
    UPDATA_TIME_UNIT_LIST
} from 'src/home/mod_cluster/project_manager/feature_manager/const_data';

import parseJson from 'src/util/parse_json.ts';

import trainingUrlAdapter from 'src/home/mod_common/training_url_adapter';
import { SfForm, SfNumberField } from '@sxf/sf-vue-component';

import store from 'src/vuex/store';
let userID = store.state.userId;
const ALGORITHM_BY_LAYER = trainingUrlAdapter(`user/${userID}/algorithm`);

export default {
    props: {
        timeFieldList: {
            type: Array,
            default: () => []
        }
    },

    data () {
        return {
            is_on: false,
            submitData: { ...TRAINING_INFO },
            algorithmConfigList: [],
            dateTime: {
                start: startTime,
                end: endTime
            },
            algorithmList: []
        }
    },

    computed: {
        form () {
            return this.$refs.form;
        },

        timeLength () {
            return this.$refs.timeLength;
        },
        showAlgorithmType () {
            return !!this.aiFlowType;
        },

        aiFlowType () {
            return +this.$route.query.aiFlowType || 0;
        },

        //选择了算法一定会有配置参数
        showConfigJson () {
            return this.submitData.isAutoMl !== 1 && this.submitData.algorithmId && this.algorithmConfigList.length > 0;
        },

        timeUnitList () {
            return UPDATA_TIME_UNIT_LIST;
        },

        defaultWidth () {
            return DEFAULT_WIDTH;
        },

        fieldWidth () {
            return DEFAULT_FEILD_WIDTH;
        },

        typeTreeOptions () {
            let list = [];
            let algorithmList = this.algorithmList;
            if (algorithmList.length > 0) {
                for (let i = 0; i < algorithmList.length; i++) {
                    let children = [];
                    for (let k = 0; k < algorithmList[i].children.length; k++) {
                        let childrenObj = {
                            id: algorithmList[i].children[k].id,
                            text: algorithmList[i].children[k].name
                        };
                        children.push(childrenObj);
                    }
                    let obj = {
                        expanded:true,
                        id:algorithmList[i].id,
                        text:algorithmList[i].name,
                        selectAble:false,
                        children
                    };
                    list.push(obj);
                }
            }
            return {
                headerHide: true,
                bufferView: false,
                autoWidth: false,
                data:list
            };
        }
    },

    watch: {
        'submitData.configJson': {
            immediate: true,
            handler () {
                this._getConfigList(this.submitData.configJson);
            }
        },
        dateTime: {
            immediate:true,
            deep:true,
            handler () {
                this.timeLengthValidate();
            }
        },
        'submitData.timeUnit' () {
            this.timeLengthValidate();
        },
        'submitData.periodic' () {
            this.timeLengthValidate();
        }
    },

    mounted () {
        this._getAlogrithmList();
    },

    methods: {
        async _getAlogrithmList () {
            let jsonData = await this.$ajax.get(ALGORITHM_BY_LAYER);
            let { success, msg, data } = jsonData;
            if (!success) {
                return this.$showErr(msg || _('加载数据失败'));
            };
            this.algorithmList = data;
        },

        timeLengthValidate () {
            if (this.submitData.periodic === 1) {
                this.submitData.startTime = moment(this.dateTime.start).valueOf();
                this.submitData.endTime = moment(this.dateTime.end).valueOf();
                this.$nextTick(()=>{
                    if (!this._getUpdateTimeFlag(this.submitData.timeLength)) {
                        this.timeLength && this.timeLength.validate();
                    } else {
                        this.timeLength && this.timeLength.clearInvalid();
                    }
                });

            }
        },

        _selectAlgorithm () {
            let list = this._getAlgorithmList();
            this.submitData.algorithmName = list.filter(item=> item.id === this.submitData.algorithmId)[0].name;
            this._getAlgorithmConfigList();
        },

        // TODO: REMOVE ANY
        _getConfigList (json) {
            this.algorithmConfigList = [];
            let formData = parseJson(json);
            this.algorithmConfigList = formData;
        },

        async _getAlgorithmConfigList () {
            const HYPERPARAMS_URL = trainingUrlAdapter(`algorithm/${this.submitData.algorithmId}/hyperParams`);
            let jsonData = await this.$ajax.get(HYPERPARAMS_URL, {algorithmId:this.submitData.algorithmId});
            this.$unmask();
            let {data} = jsonData;

            let {success, msg, data} = jsonData;
            if (!success) {
                this.$showErr(msg || _('加载数据失败'));
                return;
            };
            this._getConfigList(data);
        },

        getJsonValue () {
            this.submitData.configJson = JSON.stringify(this.algorithmConfigList);
            this.submitData.startTime = moment(this.dateTime.start).valueOf();
            this.submitData.endTime = moment(this.dateTime.end).valueOf();
            return this.submitData;
        },

        // TODO: REMOVE ANY
        setJsonValue (data) {
            this.submitData = Object.assign(this.submitData, data);

            // this.submitData.algorithmId = !data.algorithmId ? 0 : `${data.algorithmId}`;
        },

        // TODO: REMOVE ANY
        _typeTreeRender (_id, node) {
            return node.text;
        },

        isValid () {
            return this.form && this.form.isValid();
        },

        clearInvalidMsg () {
            this.$nextTick(() => {
                this.form && this.form.clearInvalid();
            });
        },

        // TODO: REMOVE ANY
        reset () {
            this.dateTime = {
                start:startTime,
                end:endTime
            };
            this.submitData = deepClone(TRAINING_INFO);
            this.submitData.startTime = startTime;
            this.submitData.endTime = endTime;
            this.$nextTick(()=>{
                this.form && this.form.clearInvalid();
            });
        },

        getInvalidMsgs () {
            return this.form && this.form.getInvalidMsgs();
        },

        // TODO: REMOVE ANY
        _timeLengthValidator (value) {
            if (!value) {
                return _('该输入项不允许为空');
            }
            if (!this._getUpdateTimeFlag(value)) {
                return _('更新时间不能大于执行时间');
            }
            return true;
        },

        // TODO: REMOVE ANY
        _getUpdateTimeFlag (value) {

            //执行时间
            let executionTime = this.submitData.endTime - this.submitData.startTime;

            //更新时间
            value = +value;
            let unit = this.submitData.timeUnit;
            let updateTime;
            /* eslint-disable no-magic-numbers */
            if (unit === 'year') {
                updateTime = 1000 * 60 * 60  * 24 * 365 * value;
            } else if (unit === 'month') {
                updateTime = 1000 * 60 * 60  * 24 * 30 * value;
            } else if (unit === 'day') {
                updateTime = 1000 * 60 * 60  * 24 * value;
            } else {
                updateTime = 1000 * 60 * 60 * value;
            }
            if (updateTime > executionTime) {
                return false;
            }

            // debugger;
            return true;
        },

        _getAlgorithmList () {
            let list = [];
            for (let i = 0; i < this.algorithmList.length; i++) {
                list.push(this.algorithmList[i].children);
            }
            let algorithmList = [].concat.apply([], list);
            return algorithmList;
        }
    }

};
</script>
<style lang="less" scoped>

    .set_algorithm_form{
        .algorithm-config__container{
            display: flex;
            align-items: center;
            margin-bottom: 12px;
        }
        .quick-algorithm{
            margin-top: 8px;
            display: inline-block;
            color: #14161a;
            font-weight: bold;
            margin-left: 3px;
        }
        .sfv-radio-group .sfv-radio{
            margin-right: 100px;
        }
        .m-l3{
            margin-left: 3px;
        }
        .save-step{
            margin-left: 12px;
            margin-bottom: 8px;
        }
        padding: 15px 0 0 0;
        margin-left: 26px;
        .sfv-form-item{
            margin-bottom: 8px;
        }
        .set-opr{
            padding-left: 124px;
            margin-bottom:0;
        }
        .time-opr{
            display: flex;
            align-items: center;
            .sfv-radio-group{
                margin-left: 4px;
            }
        }
        .save-opr{
            padding-left: 12px;
            margin-bottom: 0;
        }
        .algorithm-config__form {
            display: flex;
            flex-wrap: wrap;
            width: 456px;
            padding: 10px 10px 0 0 ;
            background: #FAFAFA;
            border: 1px solid #E0E0E0;
            margin-left: 124px;
            justify-content: space-between;
            max-height: 292px;
            overflow: auto;
            .sfv-fieldlabel{
                width: 150px !important;
            }
        }
    }
     @media screen and (max-width: 1366px) {
        .set_algorithm_form{
            height: 400px;
        }
    }
    .config__layer{
        z-index: 1100 !important;
    }
    .time-update__container{
        .sfv-steps__wrap-modal{
            margin-top: 0;
        }
        .sfv-form-item{
            margin-bottom: 10px;
        }
        .time_update_form{
            display: flex;
            align-items:center;
            .sfv-form-item{
                margin-bottom: 8px;
            }
            .m-t1{
                .sfv-radio-wrap+label{
                    margin-top: 1px;
                }
            }
        }
        .add-condition__date-picker {
            width: 326px;
            height: 30px;
            border-radius:0;
            &.allowblank-error {
                border: 1px solid #f55151;
            }
        }
        .time_update__content{
            background: #FAFAFA;
            border: 1px solid #E0E0E0;
            width: 456px;
            margin-left: 123px;
            padding: 10px;
            padding-bottom: 0;
            margin-bottom: 10px;
            margin-top: -10px;
            .config-title{
                font-size: 13px;
                color: #14161A;
                font-weight: bold;
                margin-bottom: 3px;
                .sfv-fieldtip{
                    position: relative;
                    font-size: 20px;
                    width: 30px;
                    font-weight: 100;
                    &:hover{
                        .update-demo{
                            display: block;
                        }
                    }
                }
                .update-demo{
                    display: none;
                    position: absolute;
                    z-index: 100;
                    background: #fff;
                    padding: 15px;
                    left: 27px;
                     top: -8px;
                    border: 1px solid #ddd;
                    .update-demo__img{
                        background: url(../../../img/update_demo.png);
                        background-size: 100% 100%;
                        width: 450px;
                        height: 269px;
                    }

                }
            }
            .sfv-fieldlabel-left{
                padding-left: 0;
            }
            .sfv-fieldlabel {
                width: 100px !important;
            }
        }
        .update-time__content{
            margin-left: 102px;
            margin-top: -2px;
        }
    }
</style>
